<?php

namespace App\Http\Controllers\Dashboard;

use AlibabaCloud\Client\AlibabaCloud;
use App\Http\Controllers\Controller;
use App\Http\Requests\Dashboard\AliyunVodCreateUploadVodRequest;
use App\Http\Requests\Dashboard\AliyunVodRefreshUploadVodRequest;
use Illuminate\Http\Request;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Vod\Vod;

class AliyunVodController extends Controller
{
    const VOD_CLIENT_NAME = 'DEMO';

    protected function initVodClient()
    {
        $regionId = 'cn-shanghai';
        AlibabaCloud::accessKeyClient(env('ALIYUN_ACCESS_KEY_ID'), env('ALIYUN_ACCESS_KEY_SECRET'))
            ->regionId($regionId)
            ->connectTimeout(1)
            ->timeout(3)
            ->name(self::VOD_CLIENT_NAME);
    }

    public function getPlayInfo($videoId)
    {
        $this->initVodClient();
        $playInfo = Vod::v20170321()->getPlayInfo()->client(self::VOD_CLIENT_NAME)
            ->withVideoId($videoId)// 指定接口参数
            ->withAuthTimeout(3600 * 24)
            ->format('JSON')// 指定返回格式
            ->request();      // 执行请求
        return $playInfo->toArray();
    }

    public function createUploadVideo(AliyunVodCreateUploadVodRequest $request)
    {
        $this->initVodClient();
        $aliRequest = Vod::v20170321()->createUploadVideo()->client(self::VOD_CLIENT_NAME)->withFileName($request->filename)->withTitle($request->title)->format('JSON');
        if ($request->cate_id) {
            $aliRequest = $aliRequest->withCateId($request->cate_id);
        }
        if ($request->cover_url) {
            $aliRequest = $aliRequest->withCoverURL($request->cover_url);
        }
        if ($request->tags) {
            $aliRequest = $aliRequest->withTags(implode(',', $request->tags));
        }
        if ($request->description) {
            $aliRequest = $aliRequest->withDescription($request->description);
        }
        if ($request->template_group_id) {
            $aliRequest = $aliRequest->withTemplateGroupId($request->template_group_id);
        }
        $aliRequest = $aliRequest->request();      // 执行请求
        return $aliRequest->toArray();
    }

    public function refreshUploadVideo(AliyunVodRefreshUploadVodRequest $request)
    {
        $this->initVodClient();
        $aliRequest = Vod::v20170321()->refreshUploadVideo()->client(self::VOD_CLIENT_NAME)->withVideoId($request->video_id)->format('JSON')->request();

        return $aliRequest->toArray();
    }
}
